<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * Treacle SQLite database Adapter Class file
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id $
 * @package database
 */
/**
 * SQLite database Adapter Class
 *
 * Note: _DB is an extender class that the app controller
 * creates dynamically based on whether the active record
 * class is being used or not.
 *
 * @package	database
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version	$Id $
 */
class DB_sqlite_driver extends DB
{
	/**
	 * Non-persistent database connection
	 *
	 * @access	private called by the base class
	 * @return	resource
	 */
	public function db_connect()
	{
		$this->database = APPPATH."tmp/".$this->database;
		if( !function_exists('sqlite_open'))
		{
			throw new TSystemException('你的PHP环境不支持 Sqlite 请检查你的 PHP.INI 的配置');
		}
		if (  !$conn_id = @sqlite_popen($this->database, 0666, $error))
		{
			throw new TDbException('不能链接数据库,请检查数据库或数据库所在的目录是否为可写属性');
		}
		return $conn_id;
	}

	/**
	 * Persistent database connection
	 *
	 * @access	private called by the base class
	 * @return	resource
	 */
	public function db_pconnect()
	{
		$this->database = APPPATH."tmp/".$this->database;
		if( !function_exists('sqlite_open'))
		{
			throw new TSystemException('你的PHP环境不支持 Sqlite 请检查你的 PHP.INI 的配置');
		}
		if (  !$conn_id = @sqlite_popen($this->database, 0666, $error))
		{
			throw new TDbException('不能链接数据库,请检查数据库或数据库所在的目录是否为可写属性');
		}
		return $conn_id;
	}

	/**
	 * Select the database
	 *
	 * @access	private called by the base class
	 * @return	resource
	 */
	public function db_select()
	{
		return true;
	}

	/**
	 * Version number query string
	 *
	 * @access	public
	 * @return	string
	 */
	protected function _version()
	{
		return sqlite_libversion();
	}

	/**
	 * Execute the query
	 *
	 * @access	private called by the base class
	 * @param	string	an SQL query
	 * @return	resource
	 */
	protected function _execute($sql)
	{
		$sql = $this->_prep_query($sql);
		return sqlite_query($this->conn_id, $sql);
	}

	/**
	 * Prep the query
	 *
	 * If needed, each database adapter can prep the query string
	 *
	 * @access	private called by execute()
	 * @param	string	an SQL query
	 * @return	string
	 */
	protected function _prep_query($sql)
	{
		return $sql;
	}

	/**
	 * Begin Transaction
	 *
	 * @access	public
	 * @return	bool
	 */
	public function trans_begin($test_mode = false)
	{
		if ( ! $this->trans_enabled)
		{
			return true;
		}

		// When transactions are nested we only begin/commit/rollback the outermost ones
		if ($this->_trans_depth > 0)
		{
			return true;
		}

		// Reset the transaction failure flag.
		// If the $test_mode flag is set to true transactions will be rolled back
		// even if the queries produce a successful result.
		$this->_trans_failure = ($test_mode === true) ? true : false;

		$this->simple_query('BEGIN TRANSACTION');
		return true;
	}

	/**
	 * Commit Transaction
	 *
	 * @access	public
	 * @return	bool
	 */
	public function trans_commit()
	{
		if ( ! $this->trans_enabled)
		{
			return true;
		}

		// When transactions are nested we only begin/commit/rollback the outermost ones
		if ($this->_trans_depth > 0)
		{
			return true;
		}

		$this->simple_query('COMMIT');
		return true;
	}

	/**
	 * Rollback Transaction
	 *
	 * @access	public
	 * @return	bool
	 */
	public function trans_rollback()
	{
		if ( ! $this->trans_enabled)
		{
			return true;
		}

		// When transactions are nested we only begin/commit/rollback the outermost ones
		if ($this->_trans_depth > 0)
		{
			return true;
		}

		$this->simple_query('ROLLBACK');
		return true;
	}

	/**
	 * Escape String
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	public function escape_str($str)
	{
		return sqlite_escape_string($str);
	}

	/**
	 * Affected Rows
	 *
	 * @access	public
	 * @return	integer
	 */
	public function affected_rows()
	{
		return sqlite_changes($this->conn_id);
	}

	/**
	 * Insert ID
	 *
	 * @access	public
	 * @return	integer
	 */
	public function insert_id()
	{
		return @sqlite_last_insert_rowid($this->conn_id);
	}

	/**
	 * "Count All" query
	 *
	 * Generates a platform-specific query string that counts all records in
	 * the specified database
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	public function count_all($table = '')
	{
		if ($table == '') return '0';
		$query = $this->query("SELECT COUNT(*) AS numrows FROM `".$this->dbprefix.$table."`");
		if ($query->num_rows() == 0) return '0';
		$row = $query->row();
		return $row->numrows;
	}

	/**
	 * List table query
	 *
	 * Generates a platform-specific query string so that the table names can be fetched
	 *
	 * @access	private
	 * @return	string
	 */
	protected function _list_tables()
	{
		return "SELECT name from sqlite_master WHERE type='table'";
	}

	/**
	 * Show column query
	 *
	 * Generates a platform-specific query string so that the column names can be fetched
	 *
	 * @access	public
	 * @param	string	the table name
	 * @return	string
	 */
	protected function _list_columns($table = '')
	{
		// Not supported
		return false;
	}

	/**
	 * Field data query
	 *
	 * Generates a platform-specific query so that the column data can be retrieved
	 *
	 * @access	public
	 * @param	string	the table name
	 * @return	object
	 */
	protected function _field_data($table)
	{
		return "SELECT * FROM ".$this->_escape_table($table)." LIMIT 1";
	}

	/**
	 * The error message string
	 *
	 * @access	private
	 * @return	string
	 */
	protected function _error_message()
	{
		return sqlite_error_string(sqlite_last_error($this->conn_id));
	}

	/**
	 * The error message number
	 *
	 * @access	private
	 * @return	integer
	 */
	protected function _error_number()
	{
		return sqlite_last_error($this->conn_id);
	}

	/**
	 * Escape Table Name
	 *
	 * This public function adds backticks if the table name has a period
	 * in it. Some DBs will get cranky unless periods are escaped
	 *
	 * @access	private
	 * @param	string	the table name
	 * @return	string
	 */
	protected function _escape_table($table)
	{
		if (stristr($table, '.'))
		{
			$table = preg_replace("/\./", "`.`", $table);
		}

		return $table;
	}

	/**
	 * Insert statement
	 *
	 * Generates a platform-specific insert string from the supplied data
	 *
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the insert keys
	 * @param	array	the insert values
	 * @return	string
	 */
	protected function _insert($table, $keys, $values)
	{
		return "INSERT INTO ".$this->_escape_table($table)." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
	}

	/**
	 * Update statement
	 *
	 * Generates a platform-specific update string from the supplied data
	 *
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the update data
	 * @param	array	the where clause
	 * @return	string
	 */
	protected function _update($table, $values, $where)
	{
		foreach($values as $key => $val)
		{
			$valstr[] = $key." = ".$val;
		}

		return "UPDATE ".$this->_escape_table($table)." SET ".implode(', ', $valstr)." WHERE ".implode(" ", $where);
	}

	/**
	 * Delete statement
	 *
	 * Generates a platform-specific delete string from the supplied data
	 *
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the where clause
	 * @return	string
	 */
	protected function _delete($table, $where)
	{
		return "DELETE FROM ".$this->_escape_table($table)." WHERE ".implode(" ", $where);
	}

	/**
	 * Limit string
	 *
	 * Generates a platform-specific LIMIT clause
	 *
	 * @access	public
	 * @param	string	the sql query string
	 * @param	integer	the number of rows to limit the query to
	 * @param	integer	the offset value
	 * @return	string
	 */
	protected function _limit($sql, $limit, $offset)
	{
		if ($offset == 0)
		{
			$offset = '';
		}
		else
		{
			$offset .= ", ";
		}

		return $sql."LIMIT ".$offset.$limit;
	}

	/**
	 * Close DB Connection
	 *
	 * @access	public
	 * @param	resource
	 * @return	void
	 */
	protected function _close($conn_id)
	{
		@sqlite_close($conn_id);
	}
}
/*
+---------------------------------------------------------------------------
|   Last Modified By BoPo
|   Date: Wed Sep 05 17:25:29 CST 2007
+--------------------------------------------------------------------------
*/
?>